package com.ncloud.crm.service.impl;

import java.util.Date;
import java.util.List;

import com.ncloud.param.service.SequenceService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsNodeEqpt;
import com.ncloud.crm.entity.order.WorkNodeEqpt;
import com.ncloud.crm.mapper.WorkNodeEqptMapper;
import com.ncloud.crm.service.BsNodeEqptService;
import com.ncloud.crm.service.WorkNodeEqptService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;

@Service
public class WorkNodeEqptServiceImpl implements WorkNodeEqptService {
	
	private static final Logger logger = LogManager.getLogger(WorkNodeEqptServiceImpl.class);
	
	@Autowired
	private WorkNodeEqptMapper workNodeEqptMapper;
	@Autowired
	private BsNodeEqptService bsNodeEqptService;
	@Reference
	private SequenceService sequenceService;


	public JSONArray getId(JSONObject json) {
		if(json==null || !json.containsKey("workId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		List<WorkNodeEqpt> orderAttrs = workNodeEqptMapper.getWorkNodeEqptByWorkId(json.getLong("workId"));
		return JSON.parseArray(JSON.toJSONString(orderAttrs));
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject jsonObject = new JSONObject();
		JSONArray nodeEqptArray = new JSONArray();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		if(json.containsKey(OrderNodeDefineUtils.ORDER_CONTRACT)){
			JSONArray contractInfos = json.getJSONArray(OrderNodeDefineUtils.ORDER_CONTRACT);
			for(int i=0;i<contractInfos.size();i++){
				JSONObject contractInfo = contractInfos.getJSONObject(i);
				//处理node节点
				if(contractInfo.containsKey("nodeInfos")){
					JSONArray nodes = contractInfo.getJSONArray("nodeInfos");
					for(int j=0;j<nodes.size();j++){
						JSONObject node = nodes.getJSONObject(j);
						WorkNodeEqpt workNodeEqpt =null;
						//处理节点设备 1:CPE(硬件设备)
						if(node.containsKey("equip") && Constant.NODE_TYPE_1.equals(node.getString("nodeType"))){
							JSONObject equipJson = node.getJSONObject("equip");
							workNodeEqpt = JSON.parseObject(equipJson.toJSONString(),WorkNodeEqpt.class);
							if(workNodeEqpt.getNodeId() == null){
								workNodeEqpt.setNodeId(result.getLong(TableIdDefineUtils.NODE_ID));
							}
							String eqptModifyTag = workNodeEqpt.getModifyTag();
							if(Constant.ADD.equals(eqptModifyTag)){
								/*生成设备id*/
								Long id = sequenceService.getSequence("seq_eqpt_id");
								workNodeEqpt.setEqptId(id);
								result.put(TableIdDefineUtils.EQPT_ID,id);
								workNodeEqpt.setBeginDate(new Date());
								workNodeEqpt.setEndDate(DateUtils.parseDate(Constant.END_DATE));
								workNodeEqpt.setUpdateUser(json.getLong("userId"));
							}else if(Constant.UPDATE.equals(eqptModifyTag)){
								/*根据修改的节点查询对应的实例信息，对实例做旧单操作，对改单做新增操作*/
								if(workNodeEqpt.getEqptId() != null){
									BsNodeEqpt bsNodeEqpt = bsNodeEqptService.getNodeEqptInfoByPk(workNodeEqpt.getEqptId());
									logger.debug("旧CPE信息："+JSON.toJSONString(bsNodeEqpt));
									WorkNodeEqpt workNodeEqptOld = JSON.parseObject(JSON.toJSONString(bsNodeEqpt),WorkNodeEqpt.class);

								/*旧记录*/
									workNodeEqptOld.setEndDate(new Date());
									workNodeEqptOld.setUpdateTime(new Date());
									workNodeEqptOld.setUpdateUser(json.getLong("userUser"));
									workNodeEqptOld.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
									workNodeEqptOld.setModifyTag("3");
								/*新记录*/
									workNodeEqpt.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
									workNodeEqpt.setBeginDate(new Date());
									workNodeEqpt.setEndDate(DateUtils.parseDate(Constant.END_DATE));
									workNodeEqpt.setUpdateTime(new Date());
									workNodeEqpt.setUpdateUser(json.getLong("userUser"));
									workNodeEqpt.setModifyTag("1");
									/*保存原来信息*/
									nodeEqptArray.add(JSON.parseObject(JSON.toJSONString(workNodeEqptOld)));
								}else {
									throw new UserException(ResultEnum.PARAM_ERROR);
								}

							}
						}/*else if(node.containsKey("equip") && "2".equals(node.getString("nodeType"))){
							*//*虚拟cpe设备信息*//*

						}else if(node.containsKey("equip") && "3".equals(node.getString("nodeType"))){
							//3-公有云
						}*/

						//保存节点
						nodeEqptArray.add(JSON.parseObject(JSON.toJSONString(workNodeEqpt)));
					}
				}
			}
			//最外层保存节点设备信息
			jsonObject.put(OrderNodeDefineUtils.NODE_EQPT,nodeEqptArray);
		}
		return jsonObject;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		WorkNodeEqpt nodeEqpt = JSON.parseObject(json.toJSONString(),WorkNodeEqpt.class);
		try {
			validation(nodeEqpt);
			workNodeEqptMapper.insertWorkNodeEqpt(nodeEqpt);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}
	private void validation(WorkNodeEqpt nodeEqpt){
		if(nodeEqpt.getEqptId() ==null){
			Long id = sequenceService.getSequence("seq_eqpt_id");
			nodeEqpt.setEqptId(id);
		}
	}

	@Override
	public List<WorkNodeEqpt> getNodeEqptsByWorkId(Long workId) {
		return workNodeEqptMapper.getWorkNodeEqptByWorkId(workId);
	}
	@Override
	public void eqptCPE(JSONObject node,JSONObject result,JSONArray array){
		//处理节点设备 1:CPE(硬件设备)
		WorkNodeEqpt workNodeEqpt =null;
		if(node.containsKey("equip") && Constant.NODE_TYPE_1.equals(node.getString("nodeType"))
				&& Constant.NODE_TYPE_CPE_1.equals(node.getString("nodeSubType"))){
			JSONObject equipJson = node.getJSONObject("equip");
			workNodeEqpt = JSON.parseObject(equipJson.toJSONString(),WorkNodeEqpt.class);

			/*cpe设备公共信息begin*/
			if(workNodeEqpt.getNodeId()== null){
				workNodeEqpt.setNodeId(result.getLong(TableIdDefineUtils.NODE_ID));
			}

			workNodeEqpt.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
			/*cpe设备公共信息end*/
			//String eqptModifyTag = workNodeEqpt.getModifyTag();
			String eqptModifyTag =node.getString("modifyTag");
			workNodeEqpt.setModifyTag(eqptModifyTag);
			if(Constant.ADD.equals(eqptModifyTag)){
								/*生成设备id*/
				/*Long id = sequenceService.getSequence("seq_eqpt_id");
				workNodeEqpt.setEqptId(id);
				result.put(TableIdDefineUtils.EQPT_ID,id);*/


				workNodeEqpt.setBeginDate(DateUtils.parseDate(result.getString("createDate")));
				workNodeEqpt.setEndDate(DateUtils.parseDate(Constant.END_DATE));
				workNodeEqpt.setUpdateUser(result.getLong("userID"));
			}else if(Constant.UPDATE.equals(eqptModifyTag)){
								/*根据修改的节点查询对应的实例信息，对实例做旧单操作，对改单做新增操作*/
				if(workNodeEqpt.getEqptId() != null){
					BsNodeEqpt bsNodeEqpt = bsNodeEqptService.getNodeEqptInfoByPk(workNodeEqpt.getEqptId());
					logger.debug("旧CPE信息："+JSON.toJSONString(bsNodeEqpt));
					WorkNodeEqpt workNodeEqptOld = JSON.parseObject(JSON.toJSONString(bsNodeEqpt),WorkNodeEqpt.class);

								/*旧记录*/
					workNodeEqptOld.setEndDate(DateUtils.parseDate(result.getString("createDate")));
					workNodeEqptOld.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
					workNodeEqptOld.setUpdateUser(result.getLong("userID"));
					workNodeEqptOld.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
					workNodeEqptOld.setModifyTag("3");
								/*新记录*/

					/*if(workNodeEqpt.getNodeId()== null){
						workNodeEqpt.setNodeId(result.getLong(TableIdDefineUtils.NODE_ID));
					}*/
					//workNodeEqpt.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
					workNodeEqpt.setBeginDate(DateUtils.parseDate(result.getString("createDate")));
					workNodeEqpt.setEndDate(DateUtils.parseDate(Constant.END_DATE));
					workNodeEqpt.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
					workNodeEqpt.setUpdateUser(result.getLong("userID"));
					workNodeEqpt.setModifyTag("1");
					//workNodeEqpt.setNodeInstId(result.getLong("newNodeInstId"));
									/*保存原来信息*/
					array.add(JSON.parseObject(JSON.toJSONString(workNodeEqptOld)));
				}else {
					throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"修改CPE设备信息设备id不存在！");
				}

			}else if(Constant.DEL.equals(eqptModifyTag)){
				workNodeEqpt.setEndDate(DateUtils.parseDate(result.getString("createDate")));
				workNodeEqpt.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
				workNodeEqpt.setUpdateUser(result.getLong("userID"));
			}else{
				workNodeEqpt.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
				workNodeEqpt.setUpdateUser(result.getLong("userID"));
			}
			array.add(JSON.parseObject(JSON.toJSONString(workNodeEqpt)));
		}
	}

	@Override
	public List<WorkNodeEqpt> getNewNodeEqptsByWorkId(Long workId, Long nodeId) {
		return workNodeEqptMapper.getNewNodeEqptsByWorkId(workId, nodeId);
	}
}
